<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    .box img{
        position: absolute;
    }
    .box span{
        position: absolute;
        top: 1px;
        right: 1000px;
        font-size: 50px;
        color: pink;
        cursor: pointer;
    }
</style>
<body>
    <div class="box">
        <img src="" alt="" id="pic">
        <span id="del">×</span>
    </div>
    <div>
        <input type="file" id="file">
    </div>

    <script>
        const filedom=document.querySelector("#file")
        const del=document.querySelector('#del')

        del.addEventListener('click',clickhander)
        filedom.addEventListener('change',changehander)

        function clickhander(e){
            href=pic.src.split("/").pop()
            pic.src=null
            file.value=''
            
            if(pic.src==null){
                del.removeEventListener('click',clickhander)
            }
            const xhr=new XMLHttpRequest;
               xhr.open('POST','/del');
               xhr.setRequestHeader('delname',href)
               xhr.send()
               xhr.onreadystatechange=function(){
                   if(xhr.readyState===4 && xhr.status===200){
                       let json=JSON.parse(xhr.responseText)
                       pic.src=json.url
                   }
               }

        }


        function changehander(e){
           const file= filedom.files[0]
           const fileReader=new FileReader()
           //把file对象转换成流，这样可以通过ajax发送
           fileReader.readAsArrayBuffer(file)
           fileReader.onload=function(){
               const xhr=new XMLHttpRequest;
               xhr.open('POST','/upload',true);
               xhr.setRequestHeader('filename',file.name)
               xhr.send(fileReader.result)
               xhr.onreadystatechange=function(){
                   if(xhr.readyState===4 && xhr.status===200){
                       let json=JSON.parse(xhr.responseText)
                       pic.src=json.url
                   }
               }
           }

        }
    </script>
</body>
</html>